<?php

namespace common\repositories\official;

use Yii;
use common\repositories\BaseRepository;
use common\entities\official\ArticleEntity;
use common\support\StringHelper;
use common\support\Helper;
use common\error\ErrorCode;

class ArticleRepository extends BaseRepository {

    const ARTICLE_RELEASE = 1; // 发布
    const ARTICLE_NO_RELEASE = 0; // 未发布
    const ARTICLE_DEL = 1; // 删除
    const ARTICLE_NO_DEL = 0; // 未删除
    const ARTICLE_TOP = 1; // 头版
    const ARTICLE_NO_TOP = 0; // 非头版
    
    public function __construct($config = []) {
        parent::__construct($config);
    }

    /**
     * 更新文章
     * @param type $model
     */
    public function updateArticle ($model) {
        $entity = ArticleEntity::find()->where(['a_id' => $model->aId])->one();
        if (!isset($entity)) {
            return self::setAndReturn(ErrorCode::ERR_CMS_ARTICLE_NOT_EXISTS); // 文章不存在
        }
        $model->modifiedTime = time();
        $this->setFieldEntity($entity, $model);
        $result = $entity->update();
        if ($result === false) {
            return self::setAndReturn(ErrorCode::ERR_CMS_ARTICLE_SAVE_FAIL, $entity->firstErrorMessage); // 保存错误
        } else {
            return $entity->a_id;
        }
        
    }
    
    /**
     * 创建文章
     * @param type $model
     */
    public function addArticle ($model) {
        $model->createdTime = time();
        $model->modifiedTime = time();  
        
        $entity = new ArticleEntity();
        $this->setFieldEntity($entity,$model);
        $entity->created_time = $model->createdTime;

        $result = $entity->save();
        if (false === $result) {
            return $entity->getErrors();
        }
        return $entity->a_id;
    }
    
    /**
     * 设置数据
     * @param type $entity
     * @param type $model
     */
    public function setFieldEntity(&$entity,$model) {
        $entity->modified_time = $model->modifiedTime;
        $entity->modified_by = $model->modifiedBy;
        $entity->title = $model->title;
        $entity->content = htmlspecialchars($model->content);
        $entity->tag = $model->tag;  
        $entity->image_url = $model->imageUrl;
        $entity->file_url = $model->fileUrl;
        $entity->dir_id = $model->dirId;
        $entity->file_name = $model->fileName;
        $entity->desc = $model->desc;
        $entity->created_by = $model->createdBy;
    }
    
    public function getArticleInfo ($aId) {
        $query = ArticleEntity::find()
                ->where(['a_id' => $aId])
                ->asArray()
                ->one();  
        $query['content'] = htmlspecialchars_decode($query['content']);
        return $query;
    }
    
    /**
     * 获取文章列表
     * @param type $sidx
     * @param type $sord
     * @param type $page
     * @param type $page_size
     * @param type $search
     * @return type
     */
    public function getArticleAllList ($sidx, $sord, $page, $page_size, $search="") {
        $ascText = strtolower($sord) == 'asc' ? SORT_ASC : SORT_DESC;
        $query = ArticleEntity::find();
            
        if (! empty($search)) {
            $query = $query->where(['like', 'title', $search])
                ->orwhere(['like', 'tag', $search]);
        }
        $query = $query->andwhere(['del' => 0])
            ->orderBy([$sidx => $ascText])
            ->offset((int)($page-1)*$page_size)
            ->limit((int)$page_size)                
            ->all();
        return $query;       
    }


    public function getArticleListByDirId($dirId,$limit=10) {

        $connection = ArticleEntity::getDb();
        $sql = "select a_id,dir_id,tag,title,image_url,file_url,IF(`content` = '' or `content` is null, 1 ,0) as is_empty from ".ArticleEntity::tableName()."
        where dir_id={$dirId} and del=".self::ARTICLE_NO_DEL." and status=".self::ARTICLE_RELEASE." order by sort desc,modified_time desc limit {$limit}";
        $command = $connection->createCommand($sql);
        $result = $command->queryAll();
        return $result;

//        $entity = ArticleEntity::find()->select("a_id,dir_id,tag,title,image_url,file_url,IF(`content` = '' OR `content` IS NULL , 0 ,1) as is_empty")
//            ->where(["dir_id"=>$dirId,"del"=>self::ARTICLE_NO_DEL,'status'=>self::ARTICLE_RELEASE])
//            ->orderBy('sort desc,modified_time desc')
//            ->limit($limit)
//            ->all();
//        return $entity;
    }
    
    /**
     * 批量处理
     * @param type $section
     * @param type $value
     * @param type $ids
     * @return type
     */
    public function updateBatch($section, $value, $ids) {
        $entitys = ArticleEntity::find()
                ->where(['in', 'a_id', $ids])
                ->all();
        foreach ($entitys as $entity) {
            $entity->$section = $value;
            $entity->save();
        }             
    }
}